﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using System.Threading;

namespace 主窗体
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(Rec));
            th.IsBackground = true;
            th.Start();
        }
        #region 服务端接收
        public void Rec()
        {
            while (true)
            {
                IntPtr pipeHandle = NamedPipeLib.CreateNamedPipe(
                             @"\\.\pipe\PMYMain",
                             NamedPipeLib.PIPE_ACCESS_DUPLEX,
                             NamedPipeLib.PIPE_TYPE_MESSAGE | NamedPipeLib.PIPE_READMODE_MESSAGE,
                             NamedPipeLib.PIPE_UNLIMITED_INSTANCES,
                             1024,
                             1024,
                             0,
                             IntPtr.Zero);

                uint u = NamedPipeLib.GetLastError();

                if (pipeHandle.ToInt32() == NamedPipeLib.INVALID_HANDLE_VALUE)
                {
                    MessageBox.Show("创建管道出错");
                    return;
                }

                bool connected = NamedPipeLib.ConnectNamedPipe(pipeHandle, null) ? true : (NamedPipeLib.GetLastError() == NamedPipeLib.ERROR_PIPE_CONNECTED);

                if (connected)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ReadMessage), pipeHandle);
                }
                else
                {
                    NamedPipeLib.CloseHandle(pipeHandle);
                }
            }
        }

        public static void ReadMessage(object arg)
        {
            IntPtr pipeHandle = (IntPtr)arg;

            byte[] numReadWritten = new byte[4];
            byte[] intBytes = new byte[4];

            NamedPipeLib.ReadFile(pipeHandle, intBytes, 4, numReadWritten, 0);

            int len = BitConverter.ToInt32(intBytes, 0);

            byte[] recBuffer = new byte[len];

            NamedPipeLib.ReadFile(pipeHandle, recBuffer, (uint)len, numReadWritten, 0);

            //string str = Encoding.UTF8.GetString(recBuffer);
            ShareMessage msg = BytesConvert.BytesToObject<ShareMessage>(recBuffer);
            string str = msg.MsgContent;
            MessageBox.Show(str, "主窗体收到");

            NamedPipeLib.FlushFileBuffers(pipeHandle);

            NamedPipeLib.DisconnectNamedPipe(pipeHandle);

            NamedPipeLib.CloseHandle(pipeHandle);
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            ShareMessage msg = new ShareMessage();
            msg.MsgContent = textBox1.Text;
            NamedPipeLib.SendMsg(msg);
        }


    }
}
